package com.rran.study.designpattern.behavioral.observer.repository;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.rran.study.designpattern.behavioral.observer.enums.ListenerEnums;
import com.rran.study.designpattern.behavioral.observer.factory.ListenerEnumFactory;
import com.rran.study.designpattern.behavioral.observer.listener.app.AppListener;

import java.util.List;
import java.util.Map;

/**
 * @author yy
 * @Type AppEventListenerResponse.java
 * @Desc
 * @date 2020/7/21 20:18
 */
public class AppEventListenerRepository {

    public static Map<String, List<AppListener>> appListenerMap = Maps.newConcurrentMap();


    public static List<AppListener> getListenerList(String name) {
        return appListenerMap.get(name);
    }

    static {
        ListenerEnums[] values = ListenerEnums.values();
        for (ListenerEnums value : values) {
            String eventName = value.getEvent().name();
            AppListener listener = ListenerEnumFactory.getAppListener(value);
            storeListener(eventName, listener);
        }
    }

    public static void storeListener(String eventName, AppListener listener) {
        if (appListenerMap.containsKey(eventName)) {
            List<AppListener> appListeners = appListenerMap.get(eventName);
            if (!appListeners.contains(listener)) {
                appListenerMap.get(eventName).add(listener);
            }
        } else {
            appListenerMap.put(eventName, Lists.newArrayList(listener));
        }
    }

}
